package com.example;


import android.app.Activity;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;
import android.R.drawable;

public class MyActivity extends Activity
{
    final static int MAX_TEMPO = 300;
    final static int MIN_TEMPO = 20;
    
    private Button minusButton;
    private Button plusButton;
    private Button startButton;
    private CheckBox accentuateFirstBeatBox;
    private TextView tempoDisplay;
    private SeekBar tempoSlider;
    
    //Sound related stuff
    private SoundPool soundPool;
    private int soundId, soundId2;
    private SoundThread soundThread;    
    private AudioManager audioManager;
    private int tempo;
    private boolean accentuateFirstBeat = true;
   
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setupSound();
        setContentView(R.layout.main);

        this.tempoSlider = (SeekBar)this.findViewById(R.id.seek);
        this.tempoSlider.setMax(MAX_TEMPO-MIN_TEMPO);
        this.tempoSlider.setProgress(tempoSlider.getMax()/2);
        this.tempoSlider.setThumbOffset(0); //Prevents the slider from moving outside the "track"
        
        this.tempoDisplay=(TextView)this.findViewById(R.id.tempodisplay);
        this.minusButton = (Button)this.findViewById(R.id.minus);
        this.plusButton = (Button)this.findViewById(R.id.plus);
        this.startButton = (Button)this.findViewById(R.id.start);
        this.accentuateFirstBeatBox = (CheckBox)this.findViewById(R.id.accFirstBeatCheckbox);
        this.accentuateFirstBeatBox.setChecked(accentuateFirstBeat);


        updateTempo(true);
        setupUiListeners();
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.accFirstBeatCheckbox:     Toast.makeText(this, "You pressed the icon!", Toast.LENGTH_LONG).show();
                break;
                    }
        return true;
    }

    /**
     * Updates the tempo and needed displays.
     * @param fromSeekBar true if tempo is changed via seekbar, false if from +- buttons
     */
    private void updateTempo(boolean fromSeekBar)
    {
        if (fromSeekBar) {
            tempo = tempoSlider.getProgress() + MIN_TEMPO;
        }
        else {
            tempoSlider.setProgress(tempo - MIN_TEMPO);
        }

        tempoDisplay.setText("Tempo:\n" +tempo);
        soundThread.setTempo(tempo);
    }

    /**
     * Loads sound files and initializes audio.
     */
    private void setupSound()
    {
        // Set the hardware buttons to control the music
        this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
        // Load the sound
        soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);

        //Does not seem to exist in Android version < 2.2...
        /*soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
            @Override
            public void onLoadComplete(SoundPool soundPool, int sampleId,
                                       int status) {
                loaded = true;
            }
        });*/

        //Sets which sound to play
        soundId = soundPool.load(this, R.raw.click1, 1);
        soundId2 = soundPool.load(this, R.raw.click2, 1);
        audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        soundThread = new SoundThread(soundPool, audioManager, soundId, soundId2, accentuateFirstBeat);
        //soundThread.setPriority(Thread.MAX_PRIORITY);
        soundThread.setTempo(tempo);
        soundThread.run();
        //soundThread.start();
    } 
    
    @Override
    public void onDestroy() {
        if(soundThread != null)
        {
            if(soundThread.isRunning()) {
                soundThread.toggle();
            }


            /*try {
                soundThread.join();
            }
            catch (InterruptedException e) {
                Log.e("SoundThread join", e.getMessage());
            }*/
        }
        super.onDestroy();
    }

    /**
     * Initializes listeners for the buttons, seekbar and checkbox(es).
     */
    private void setupUiListeners() {
        this.minusButton.setOnClickListener
                (new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        if (tempo <= MIN_TEMPO)
                            return;
                        tempo --;
                        updateTempo(false);                        
                    }
                } );

        this.plusButton.setOnClickListener
                (new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        if (tempo >= MAX_TEMPO)
                            return;
                        tempo ++;
                        updateTempo(false);
                    }
                } );

        this.startButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                soundThread.toggle();
            }

        });
        
        this.accentuateFirstBeatBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                soundThread.setAccentuateFirstBeat(((CheckBox) v).isChecked());
            }
        });
        
        this.tempoSlider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (!fromUser)
                    return;

                updateTempo(true);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                //To change body of implemented methods use File | Settings | File Templates.
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //To change body of implemented methods use File | Settings | File Templates.
            }
        });
    }
}
